package com.innovation.wjrpc.handle;

import com.innovation.wjrpc.codec.Decoder;
import com.innovation.wjrpc.codec.Encoder;
import com.innovation.wjrpc.protocol.Request;
import com.innovation.wjrpc.protocol.Response;
import com.innovation.wjrpc.protocol.StatusCheck;
import com.innovation.wjrpc.server.ServiceInstance;
import com.innovation.wjrpc.server.ServiceInvoker;
import com.innovation.wjrpc.server.ServiceManager;
import com.innovation.wjrpc.transport.RequestHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author innoyiya
 * @date 2021/9/9 10:37
 */
@Slf4j
@AllArgsConstructor
public class HTTPRequestHandler implements RequestHandler {
    private Decoder decoder;
    private Encoder encoder;
    private ServiceManager serviceManager;
    private ServiceInvoker serviceInvoker;

    @Override
    public void onRequest(InputStream receive, OutputStream toResp) {
        Response response = new Response();
        try {
            byte[] inBytes = IOUtils.readFully(receive, receive.available());
            Request request = decoder.decode(inBytes, Request.class);
            log.info("get request: {}", request);

            ServiceInstance sis = serviceManager.lookUp(request);
            Object ret = serviceInvoker.invoke(sis, request);

            response.setData(ret);
            StatusCheck.setTreated(response);

        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            StatusCheck.setFail(response);
            response.setMessage("RpcService got error: " + e.getClass().getName() + " : " + e.getMessage());
        }finally {
            byte[] outBytes = encoder.encode(response);
            try {
                toResp.write(outBytes);
                log.info("response client");
            } catch (IOException e) {
                log.warn(e.getMessage(), e);
            }
        }
    }
}
